<?php

namespace app\controller;

use app\model\Room;
use app\model\User;
use GatewayWorker\Lib\Gateway;
use support\Request;

class IndexController
{
    /**
     * @param Request $request
     * @return \support\Response
     * @author xqiaochina@163.com
     */
    public function index(Request $request)
    {
        return view('index/index');
    }

    /**
     * @param string $token
     * @return \support\Response
     * @author xqiaochina@163.com
     * 验证登录
     */
    private function checkUserLogin(string $token)
    {
        $User = new User();
        if ($User -> checkToken($token) === false) {
            return json(['code' => 0,'msg' => '请先登录']);
        }
    }

    /**
     * @param Request $request
     * @return \support\Response
     * @author xqiaochina@163.com
     * 用户登录
     */
    public function doLogin(Request $request)
    {
        $request = $request -> post();
        if (empty($request['nickname'])) {
            return json(['code' => 0,'msg' => '请输入昵称']);
        }
        if (empty($request['password'])) {
            return json(['code' => 0,'msg' => '请输入密码']);
        }
        $User = new User();
        $result = $User -> doLogin($request);
        if (false === $result) {
            return json(['code' => 0,'msg' => '登录失败']);
        }
        return json(['code' => 1,'msg' => '登录成功','data' => ['token' => $result]]);
    }


    /**
     * @param Request $request
     * @return \support\Response
     * @author xqiaochina@163.com
     * 创建聊天室
     */
    public function createRoom(Request $request)
    {
        $data = $request -> post();
        $token = $request -> header('token','');
        $this -> checkUserLogin($token);
        if (empty($data['name'])) {
            return json(['code' => 0,'msg' => '请输入房间名称']);
        }
        // 根据token 查询用户信息
        $userModel = new User();
        $userInfo = $userModel -> getUserInfoByToken($token);
        if (empty($userInfo)) {
            return json(['code' => 1005,'msg' => '请重新登录']);
        }
        $roomModel = new Room();
        $result = $roomModel -> createRoom($userInfo -> id,$data['name']);
        if (false === $result) {
            return json(['code' => 0,'msg' => '创建失败请重试']);
        }
        return json(['code' => 1,'msg' => '创建成功','room_id' => $result]);
    }

    /**
     * @param Request $request
     * @return \support\Response
     * @author xqiaochina@163.com
     */
    public function joinRoom(Request $request)
    {
        return view('index/joinRoom');
    }




}
